const puppeteer = require("puppeteer");
const moment = require("moment");

const {createMobile, config} = require("../../../common/mobile");
const {
    info,
    saveFile,
    logging,
    timeout,
    reporter,
    pickOne
} = require("../../../common/util");

const name = "vodafone";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/nl/vd/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

const links = [
    `http://www.thecapitalland.com/cpa.php?ads_id=300060&param1=hCtTbC4etotAwT-z1xny3u0r5&param2=84563`,
    `http://www.thecapitalland.com/cpa.php?ads_id=300060&param1=rCpTbC4e3oggwA-mub91hdgba&param2=84563`,
    `http://www.thecapitalland.com/cpa.php?ads_id=300060&param1=zCsT0Ckeao43lq-2melot8464&param2=84563`
];

(async () => {
    const browser = await puppeteer.launch(config);
    const page = await browser.newPage();

    const m = await createMobile(page);

    //sub status linstener
    m._page.on("response", response => {
        let url = response.url();
        let status = response.status();

        if (url.startsWith("http")) {
            logger.info(`${response.request().method()}`, status, url);
        }

        if (
            url.startsWith("https://services.dimoco.at/dcb/") &&
            url.endsWith("/ok")
        ) {
            r.s("success");
        }

        if (url.startsWith("http://google.com")) {
            r.w("failure", url);
            m.close();
        }
    });

    //开始
    try {
        r.i("start");

        logger.info("start");

        await m.get(pickOne(links));

        //等待页面加载完成
        await m._page.waitForSelector("button[class='center-block']");

        //保存页面
        saveFile(`${logdir}/1.html`, await m._page.content());

        // 点击订阅按钮
        await m.evaluate(() => {
            document.getElementsByClassName("center-block")[0].click();
        });

        logger.info("page1 click");

        await m._page.waitForNavigation();
        await m._page.waitForSelector("button[class='red-btn new-button']");

        saveFile(`${logdir}/2.html`, await m._page.content());

        // 订阅
        await m.evaluate(() => {
            document.getElementsByClassName("red-btn new-button")[0].click();
        });

        logger.info("submit");

        await m._page.waitForNavigation({timeout});

        logger.info("end");
        r.i("end");
    } catch (e) {
        saveFile(`${logdir}/error.html`, await m._page.content());
        r.e(e + "");
        logger.error(e);
    } finally {
        await m.close();
    }
    await browser.close();
})();
